# import pandas as pd
# #
# # # 读取原始数据文件
# # # df = pd.read_csv("2014_to_2021_E7_depth150-CPUE.csv")
# df = pd.read_csv(r"D:\resources\data-processing\monthly\jumbo_2020-2021M_0.25deg_ST_SSS_DO_CHL_SSH_MLD.csv")
# #
# # 创建一个新列用于存储标签，初始化为0（非中心渔场）
# df['Label'] = 0
#
# # 按每月划分，计算CPUE的上三分位数，并设置标签
# for month in df['Month'].unique():
#     monthly_df = df[df['Month'] == month]
#     # threshold = monthly_df['CPUE'].quantile(0.75)  # 上三分位数
#     threshold = monthly_df['CPUE'].quantile(0.5)  # 上三分位数
#     df.loc[(df['Month'] == month) & (df['CPUE'] >= threshold), 'Label'] = 1  # 中心渔场
#
# # 保存为新CSV文件
# # df.to_csv("CPUE_center_vs_noncenter.csv", index=False)
# df.to_csv(r"D:\resources\data-processing\monthly\jumbo_2020-2021M_0.25deg_ST_SSS_DO_CHL_SSH_MLD_0.5label.csv", index=False)
#
# print("新文件已保存为：CPUE_center_vs_noncenter.csv")


import pandas as pd

# 假设数据文件为 "fishery_data.csv"，包含 Year, Month, Lon, Lat, CPUE
# df = pd.read_csv(r"D:\resources\data-processing\monthly\jumbo_2020-2021M_0.25deg_ST_SSS_DO_CHL_SSH_MLD.csv")
df = pd.read_csv(r"D:\resources\data\jumbo\2014-2020_1deg_st_merged_st_chl_ssh_mld_CPUE_Label.csv")

# 按 Year, Month 分组，计算下三分位数 T1
def label_region(group):
    # 计算该组的 CPUE 第一三分位数 (33%)
    T1 = group['CPUE'].quantile(0.33)
    # 定义高、低产渔区
    group['Label'] = (group['CPUE'] > T1).astype(int)
    return group

# 应用到每个 (Year, Month) 分组
# df = df.groupby(['Year', 'Month'], group_keys=False).apply(label_region)
df = df.groupby(['Year'], group_keys=False).apply(label_region)

# 保存结果
# df.to_csv(r"D:\resources\data-processing\monthly\jumbo_2020-2021M_0.25deg_ST_SSS_DO_CHL_SSH_MLD_median.csv", index=False)
# df.to_csv(r"D:\resources\data\jumbo_2020-2021M_0.25deg_ST_SSS_DO_CHL_SSH_MLD_each_year_median.csv", index=False)
df.to_csv(r"D:\resources\data\jumbo\2014-2020_1deg_st_merged_st_chl_ssh_mld_CPUE_Label.csv", index=False)

print("处理完成，已生成带 Label 的数据文件 jumbo_2020-2021M_0.25deg_ST_SSS_DO_CHL_SSH_MLD_median.csv")
print(df.head())
